const express = require("express");
const router = express.Router();
const db = require("../db");

router.post("/add", (req, res) => {
  const unitInfo = req.body;
  //对客户端的数据进行校验
  if (unitInfo.unitName === "") {
    return res.send({
      success: false,
      message: "单位名称不能为空",
    });
  }
  let sql = "select * from selection_unit where unitName=?";
  db.query(sql, [unitInfo.unitName], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    if (result.length > 0) {
      return res.cc("部门名称已被占用!");
    }
    // 定义 SQL 语句
    let sql1 = "insert into selection_unit set ?";
    // 调用 db.query() 执行 sql 语句
    db.query(
      sql1,
      {
        unitName: unitInfo.unitName,
        unitType: unitInfo.unitType,
        unitAddress: unitInfo.unitAddress,
        remark: unitInfo.remark,
        createdTime: Date.now(), // 例如 createdTime 使用 Date.now() 来获取当前时间戳
      },
      (error, result) => {
        if (error) return res.cc(error);
        // 判断影响行数是否为 1
        if (result.affectedRows !== 1) return res.cc("新增部门失败！");
        return res.cc("新增部门成功", true);
      }
    );
  });
});

router.delete("/delete", (req, res) => {
  const unitInfo = req.body;
  //对客户端的数据进行校验
  if (unitInfo.unitId === "") {
    return res.send({
      success: false,
      message: "单位编码不能为空",
    });
  }
  // 执行定义好的登录函数
  let sql = "select * from selection_unit where unitId=?";
  db.query(sql, [unitInfo.unitId], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    console.log("this1----", result);
    if (result.length === 0) {
      return res.cc("未找到该部门!");
    }
    // 定义 SQL 语句
    const sql1 = "delete from selection_unit where unitId=?";
    // 调用 db.query() 执行 sql 语句
    db.query(sql1, unitInfo.unitId, (error, result) => {
      if (error) return res.cc(error);
      // 判断影响行数是否为 1
      if (result.affectedRows !== 1) return res.cc("删除部门失败！");
      return res.cc("删除部门成功", true);
    });
  });
});

router.put("/update", (req, res) => {
  const unitInfo = req.body;
  //对客户端的数据进行校验
  if (unitInfo.unitId === "") {
    return res.send({
      success: false,
      message: "单位id不能为空",
    });
  }
  // 执行定义好的登录函数
  let sql = "select * from selection_unit where unitId=?";
  db.query(sql, [unitInfo.unitId], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    if (result.length === 0) {
      return res.cc("未找到该部门!");
    }
    // 定义 SQL 语句
    const sql1 =
      "update selection_unit set unitName=?, unitType=?, remark=?, unitAddress=? where unitId=?";
    // 调用 db.query() 执行 sql 语句
    db.query(
      sql1,
      [
        unitInfo.unitName,
        unitInfo.unitType,
        unitInfo.remark,
        unitInfo.unitAddress,
        unitInfo.unitId,
      ],
      (error, result) => {
        if (error) return res.cc(error);
        // 判断影响行数是否为 1
        if (result.affectedRows !== 1) return res.cc("修改部门失败！");
        return res.cc("修改部门成功", true);
      }
    );
  });
});

router.post("/list", (req, res) => {
  const { page = 1, limit = 10, unitName = "" } = req.body;
  const offset = (page - 1) * limit;

  // 构建基础查询和参数
  let baseQuery = " FROM selection_unit WHERE 1=1";
  let params = [];

  if (unitName) {
    baseQuery += " AND unitName LIKE ?";
    params.push(`%${unitName}%`);
  }

  // 构建 SQL 计数查询语句
  const sqlCount = `SELECT COUNT(*) AS total ${baseQuery}`;

  // 查询总条数
  db.query(sqlCount, params, (error, countResults) => {
    if (error) {
      return res.cc(error);
    }
    const total = countResults[0].total;

    // 构建 SQL 查询语句
    let sql = `SELECT * ${baseQuery} LIMIT ? OFFSET ?`;
    params.push(limit, offset);
    // 执行查询
    db.query(sql, params, (error, results) => {
      if (error) {
        return res.cc(error);
      }
      return res.cc("获取记录成功", true, results, {
        total,
        page,
        limit,
      });
    });
  });
});

module.exports = router;
